﻿/// <reference path="../../_references.js" />
(function (e) {
    e.views = e.views || {};
    e.views.edituser = e.view.define({
        templateName: "tmpl_edituser",
        repo: null,
        model: null,
        ViewModel: function (data) {
            this.title = loc.newUser;
            this.Id = data.User.Id;
            this.FirstName = ko.observable(data.User.FirstName || "");
            this.LastName = ko.observable(data.User.LastName || "");
            this.Email = ko.observable(data.User.Email || "");
            this.CompanyId = ko.observable(data.User.CompanyId || "");
            this.Info = ko.observable(data.User.Info || "");
            this.Pass = ko.observable("");
            this.PasswordConfirm = ko.observable("");
            this.Phone = ko.observable(data.User.Phone || "");
            this.Companies = data.Companies;
        },
        load: function (state) {
            var that = this;
            that.repo = new e.repositories.users();
            that.repo.getEditViewModel(state.id, function (err, data) {
                that.model = new that.ViewModel(data);
                that.render(that.model);
            });
        },
        refresh: function (state) {
            this.load(state);
        },
        afterRender: function () {
            var that = this;
            that.cont.find("input[name=FirstName]").focus();
            that.cont.find("#edituserform").validate(e.validateOptions({
                rules: {
                    PasswordConfirm: {
                        equalTo: "#Pass"
                    }
                },
                messages: {
                    FirstName: {
                        required: loc.validation.firstNameReq
                    },
                    LastName: {
                        required: loc.validation.lastNameReq
                    }
                },
                submitHandler: function (form) {
                    if (that.model.Id == "0") {
                        that.repo.createUser($(form).serializeObject(), function(err, user) {
                            if (!err) {
                                e.changeView("users");
                                e.flash.success("User successfully created.");
                            }
                        });
                    } else {
                        //TODO: implement
                        e.flash.info("Editing users not supported yet");
                    }
                    return false;
                }
            }));
        },
        unload: function () {
        }
    });
} (this.eg = this.eg || {}));